package com.adcc.loadsheet.billing.service.impl;

import com.adcc.loadsheet.billing.entity.SystemConfigEntity;
import com.adcc.loadsheet.billing.security.UserInfo;
import com.adcc.loadsheet.billing.service.SystemConfigService;
import com.adcc.loadsheet.billing.util.DateTimeUtil;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.util.SystemOperationLogType;
import com.adcc.loadsheet.billing.vo.SystemConfigEntityVO;
import org.springframework.stereotype.Service;

/**
 * 系统配置Service实现类
 * Created by zhaoml on 2020/9/4.
 */
@Service
public class SystemConfigServiceImpl extends BasisServiceImpl implements SystemConfigService {

    //查询配置
    @Override
    public SystemConfigEntityVO getSystemConfig(String key){
        SystemConfigEntity systemConfigEntity = systemConfigEntityMapper.getSystemConfig(key);
        return systemConfigEntity == null ? null : systemConfigEntity.toVO();
    }

    //编辑配置
    @Override
    public String edit(SystemConfigEntityVO systemConfigEntityVO){
        try {
            SystemConfigEntity systemConfigEntity = systemConfigEntityVO.toEntity();
            UserInfo user = userContext.getCurrentUser();
            systemConfigEntity.setUpdateAt(DateTimeUtil.getNowDate());
            systemConfigEntity.setUpdateUser(user.getUsername());
            //保存配置
            SystemConfigEntity dbEntity = systemConfigEntityMapper.getSystemConfig(systemConfigEntity.getConfigKey());
            if(dbEntity == null){   //查数据库是否已存在
                systemConfigEntity.setCreateAt(DateTimeUtil.getNowDate());
                systemConfigEntity.setCreateUser(user.getUsername());
                systemConfigEntityMapper.insert(systemConfigEntity);

                //记录操作日志
                LogUtil.operationLog(SystemOperationLogType.AutomaticProcessingBills_Operation.ordinal(), "新增系统配置：设置自动生成账单时间为每月" + systemConfigEntity.getConfigValue() + "号", user.getUsername());
            }else {
                systemConfigEntityMapper.update(systemConfigEntity);
                //记录操作日志
                if(!systemConfigEntity.getConfigValue().equals(dbEntity.getConfigValue())){
                    LogUtil.operationLog(SystemOperationLogType.AutomaticProcessingBills_Operation.ordinal(), "修改系统配置：自动生成账单时间由每月" + dbEntity.getConfigValue() + "号修改为每月" + systemConfigEntity.getConfigValue() + "号", user.getUsername());
                }
            }
            return "编辑成功！";
        }catch (Exception ex) {
            throw ex;
        }
    }
}